<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-18
 * Time: 18:26
 */

namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\model\CouponUser;
use app\api\service\coupon\CouponSer;
use app\api\service\Token;

class Coupon extends BaseController
{
    /**
     * 获取可使用优惠劵
     */
    public function getCouponList($price)
    {
        $uid = Token::getCurrentUid();
        $time = time();
        $where[] = ['start_time','elt',$time];
        $where[] = ['end_time','egt',$time];
        $where[] = ['user_id','eq',$uid];
        $where[] = ['amount_of_money_use','elt',$price];
        $where[] = ['surplus_times','gt',0];
        return CouponUser::where($where)->select()->each(function ($item){
            $item['start_date'] = date('Y-m-d',$item['start_time']);
            $item['end_date'] = date('Y-m-d',$item['end_time']);
            $item['price'] = round($item['money']/$item['usage_times'],2);
            $item['checked'] = false;
        })->toArray();
    }

    /**
     * 获取用户优惠券
     */
    public function getCouponListByUser()
    {
        $uid = Token::getCurrentUid();
        $where[] = ['user_id','eq',$uid];
        $time = time();
        return CouponUser::where($where)->select()->each(function ($item) use($time){
            $item['time'] = $time;
            $item['start_date'] = date('Y-m-d',$item['start_time']);
            $item['end_date'] = date('Y-m-d',$item['end_time']);
            $item['price'] = round($item['money']/$item['usage_times'],2);
        })->toArray();
    }


    /**
     * 订单使用优惠券
     */
    public function changeCouponByOrder($type,$coupon_use_id,$order_id)
    {
        $couponOrderSer = new CouponOrderSer($type,$coupon_use_id,$order_id);
        return $couponOrderSer->entrance();
    }
}